/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.merak.core.text.json.jsonfiers;

import org.merak.core.text.json.JsonContext;
import org.merak.core.text.json.TemplateObject;
import org.merak.core.text.json.TemplateProperty;

public class ObjectJsonfier extends Jsonfier {

	//~ Methods //////////////////////////////////////////////////////////////////
	//****************************************************************************
	@Override
	public void render(Object object,JsonContext context) throws Exception {

		// Base Case
		TemplateObject template = context.getTemplate(object);
		if (template.notHasGetters()) {
			context.getBuffer().append("{}");
			return;
		}

		// Auxiliary
		StringBuffer       json       = context.getBuffer();
		TemplateProperty[] properties = template.getGettableAttributes();
		Object             value      = null;

		// Render properties
		json.append('{');		
		for (TemplateProperty property : properties) {
			// Render property's name
			json.append('"').append(property.getName()).append('"').append(':');			
			// Render property's value
			value = property.getValue(object);
			if (property.hasJsonfier()) {
				property.getJsonfier().render(value,context) ;	
			}
			else {
				context.render(value);				
			}
			// Render property separator
			json.append(',');
		}
		json.setCharAt(json.length()-1, '}');

	}
	//****************************************************************************

}
